package client

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"gin-epg/internal/app/dao"
	"gin-epg/internal/app/entity"
	"github.com/go-resty/resty/v2"
	"time"
)

// ADY 频道名称映射
var mapAdy = map[string]string{
	"812": "岳阳新闻",
	// 更多键值对...
}

// HandleAdyCron 处理 ADY 节目单
func HandleAdyCron(beforeDay, afterDay int) error {
	dao.Logger.Infof("handleAdyCron start")
	source := "ady"

	client := resty.New()
	for key, value := range mapAdy {
		dao.Logger.Infof("Key: %s, Value: %s", key, value)
		for dayOffset := -beforeDay; dayOffset <= afterDay; dayOffset++ {
			urlDate := time.Now().AddDate(0, 0, dayOffset).Format("2006-01-02")
			dao.Logger.Infof(urlDate)
			url := fmt.Sprintf("https://programme.guangdianyun.tv/v1/programme/Index/getListByChannel?channelId=%s&week=3&date=%s", key, urlDate)

			resp, err := client.R().
				SetHeaders(map[string]string{
					"Content-Type": "application/json;charset=utf-8",
					"User-Agent":   "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
				}).
				Get(url)

			if err != nil {
				return fmt.Errorf("failed to get data from URL: %v", err)
			}

			var data map[string]interface{}
			if err := json.Unmarshal(resp.Body(), &data); err != nil {
				return fmt.Errorf("failed to unmarshal JSON: %v", err)
			}

			if data["code"].(float64) == 200 && data["data"] != nil {
				if list, ok := data["data"].(map[string]interface{})["list"].([]interface{}); ok {
					// 获取当前日期范围内的已有节目记录
					db := dao.SqlSession
					dateParsed, _ := time.Parse("2006-01-02", urlDate)
					var existingRecords []entity.EpgProgramCollect
					if err := db.Where(&entity.EpgProgramCollect{Channel: value, Date: entity.NullDate{sql.NullTime{Time: dateParsed, Valid: true}}, Source: source}).Find(&existingRecords).Error; err != nil {
						dao.Logger.Errorf("failed to get existing records: %v", err)
						continue
					}

					existingMap := make(map[string]*entity.EpgProgramCollect)
					for i := range existingRecords {
						existingMap[existingRecords[i].Start] = &existingRecords[i]
					}

					var newPrograms, updatePrograms, deletePrograms []entity.EpgProgramCollect

					for _, item := range list {
						itemMap := item.(map[string]interface{})
						startTimeStr := itemMap["startTime"].(string)
						stopTimeStr := itemMap["endTime"].(string)
						title := itemMap["name"].(string)
						desc := ""

						startTime := urlDate + "T" + startTimeStr + "+08:00"
						momentStartDate, _ := time.Parse("2006-01-02T15:04:05+08:00", startTime)
						stopTime := urlDate + "T" + stopTimeStr + "+08:00"
						momentStopDate, _ := time.Parse("2006-01-02T15:04:05+08:00", stopTime)

						channel := value
						date := momentStartDate.Format("2006-01-02")
						start := momentStartDate.Format("15:04")
						stop := momentStopDate.Format("15:04")

						if channel != "" && date != "" && start != "" && stop != "" {
							if existingRecord, ok := existingMap[start]; ok {
								if existingRecord.Title != title || existingRecord.End != stop {
									existingRecord.Title = title
									existingRecord.Desc = desc
									existingRecord.End = stop
									existingRecord.UpdateTime = entity.NullTime{sql.NullTime{Time: time.Now(), Valid: true}}
									updatePrograms = append(updatePrograms, *existingRecord)
								}
								delete(existingMap, start)
							} else {
								newRecord := entity.EpgProgramCollect{
									Title:      title,
									Desc:       desc,
									Source:     source,
									Channel:    channel,
									Date:       entity.NullDate{sql.NullTime{Time: dateParsed, Valid: true}},
									Start:      start,
									End:        stop,
									CreateTime: entity.NullTime{sql.NullTime{Time: time.Now(), Valid: true}},
								}
								newPrograms = append(newPrograms, newRecord)
							}
						}
					}

					// 处理需要删除的记录
					for _, record := range existingMap {
						deletePrograms = append(deletePrograms, *record)
					}

					// 执行数据库操作
					if len(updatePrograms) > 0 {
						for _, program := range updatePrograms {
							if err := db.Model(&program).Updates(entity.EpgProgramCollect{Title: program.Title, Desc: program.Desc, End: program.End, UpdateTime: program.UpdateTime}).Error; err != nil {
								dao.Logger.Errorf("update error: %v", err)
							} else {
								dao.Logger.Debugf("update success: %v", program)
							}
						}
					}

					if len(newPrograms) > 0 {
						for _, program := range newPrograms {
							if err := db.Create(&program).Error; err != nil {
								dao.Logger.Errorf("insert error: %v", err)
							} else {
								dao.Logger.Debugf("insert success: %v", program)
							}
						}
					}

					if len(deletePrograms) > 0 {
						for _, program := range deletePrograms {
							if err := db.Delete(&program).Error; err != nil {
								dao.Logger.Errorf("delete error: %v", err)
							} else {
								dao.Logger.Debugf("delete success: %v", program)
							}
						}
					}
				}
			}
		}
	}
	return nil
}
